package avicit.bdp.dcs.alert.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.enums.JobType;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.dcs.alert.dao.DcsAlertDao;
import avicit.bdp.dcs.alert.dto.AlertDTO;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.job.service.DcsJobService;
import avicit.bdp.dcs.tools.enums.AlertStatus;
import avicit.bdp.dcs.tools.enums.SyncStatus;
import avicit.bdp.dcs.tools.enums.TransferStatus;
import avicit.bdp.dcs.utils.DcsErrorCode;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2020-06-29
 * @类说明：告警配置Service 
 * @修改记录：
 */
@Service
@Transactional
public class AlertService extends BaseService<DcsAlertDao, AlertDTO> {

  private static final Logger logger = LoggerFactory.getLogger(AlertService.class);

  @Autowired private DcsJobService jobService;
  @Autowired private ConvertColumnClient convertColumnClient;

  public void save(String jobId, int jobType) {
    AlertDTO alertDTO = new AlertDTO();
    alertDTO.setId(ComUtil.getId());
    alertDTO.setJobId(jobId);

    int monitorItem = 0;
    if (jobType == JobType.TRANSFER.getCode()) {
      monitorItem = JobType.TRANSFER.getCode();
    } else {
      monitorItem = JobType.SYNC.getCode();
    }
    alertDTO.setMonitorItem(monitorItem);

    alertDTO.setAlertRule(String.valueOf(TransferStatus.TRANSFER_FAIL.getCode()));
    alertDTO.setAlertStatus(AlertStatus.ENABLE.getCode());

    this.insert(alertDTO);

    // 记录日志
    BdpLogUtil.log4Insert(alertDTO);
  }

  public AlertDTO getAlertById(String id) {
    AlertDTO alertDTO = this.selectByPrimaryKey(id);
    if (alertDTO == null) {
      throw new BusinessException(String.format("id:%s 的告警数据不存在", id));
    }

    BdpLogUtil.log4Query(alertDTO);
    return alertDTO;
  }

  public List<AlertDTO> getAlertListByJobId(String jobId) throws Exception {
    JobDTO jobDTO = jobService.selectByPrimaryKey(jobId);
    if (jobDTO == null) {
      throw new BusinessException(String.format(DcsErrorCode.JOB_NULL.getDesc(), jobId));
    }

    AlertDTO alertDTOQuery = new AlertDTO();
    alertDTOQuery.setJobId(jobId);
    List<AlertDTO> alertDTOList = this.selectList(alertDTOQuery);
    if (CollectionUtils.isNotEmpty(alertDTOList)) {
      for (AlertDTO alert : alertDTOList) {
        if (jobDTO.getJobType() == JobType.TRANSFER.getCode()) {
          alert.setAlertRuleName(
              TransferStatus.getEumByCode(Integer.parseInt(alert.getAlertRule())).getDescp());
        } else {
          alert.setAlertRuleName(
              SyncStatus.getEumByCode(Integer.parseInt(alert.getAlertRule())).getDescp());
        }

        // 把用户id转成用户名
        alert.setUserNames(this.convertName(alert.getUserIds()));
      }
    }
    return alertDTOList;
  }

  public void updateAlert(AlertDTO alertDTO) {
    if (StringUtils.isEmpty(alertDTO.getAlertRule())) {
      throw new BusinessException("报警规则必填");
    }
    AlertDTO alert = this.selectByPrimaryKey(alertDTO.getId());
    if (alert == null) {
      throw new BusinessException(String.format("id:%s 的告警数据不存在", alertDTO.getId()));
    }

    // 记录日志
    BdpLogUtil.log4Update(alertDTO, alert);

    alert.setAlertRule(alertDTO.getAlertRule());
    alert.setUserIds(alertDTO.getUserIds());
    this.updateByPrimaryKeySelective(alert);
  }

  public void updateAlertStatus(AlertDTO alertDTO) {
    AlertDTO alert = this.selectByPrimaryKey(alertDTO.getId());
    if (alert == null) {
      throw new BusinessException(String.format("id:%s 的告警数据不存在", alertDTO.getId()));
    }
    alert.setAlertStatus(alert.getAlertStatus() == 0 ? 1 : 0);
    this.updateByPrimaryKeySelective(alert);
  }

  // 根据用户ID调用平台服务返回用户名称
  private String convertName(String userIds) throws Exception {
    if (StringUtils.isEmpty(userIds)) {
      return null;
    }

    // 循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>(16);
    String[] array = userIds.split(Constants.COMMA);
    for (String userId : array) {
      BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, userId);
    }

    StringBuffer buf = new StringBuffer("");
    if (convertFormData.size() > 0) {
      // 获取请求结果
      Map<String, Map<String, String>> convertResultData =
          convertColumnClient.replace(convertFormData);
      // 循环设置Alias或Name的值
      for (String userId : array) {
        String name = BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, userId);
        buf.append(name).append(Constants.COMMA);
      }
    }

    String names = buf.toString();
    if (names.length() >= 1) {
      names = names.substring(0, names.length() - 1);
    }
    return names;
  }
}
